/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package edu.capex.javacore.sockets;

import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.net.InetAddress;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.HashMap;
import java.util.Random;

/**
 *
 * @author IK
 */
public class ChatServer {

    public static void main(String[] args) {
        System.out.println("Iniciando servidor");
        servidorChat servidor = new servidorChat();
        servidor.start();
        System.out.println("Servidor iniciado");
    }
}

class servidorChat extends Thread {

    private HashMap<Long, Socket> mapaClientes;
    private Random random;

    public servidorChat() {
        random = new Random();
        mapaClientes = new HashMap<Long, Socket>();
    }

    @Override
    public void run() {
        while (this.isAlive()) {
            runServer();
        }
    }

    public void runServer() {
        ServerSocket server;
        try {
            server = new ServerSocket(2000, 1, InetAddress.getLocalHost());
            Socket cox = server.accept();
            mapaClientes.put(random.nextLong(), cox);

            manejadorConexiones manager = new manejadorConexiones(cox);
            manager.start();



        } catch (Exception ex) {
            System.out.println(ex.getMessage());
        }
    }
}

class manejadorConexiones extends Thread {

    Socket connection;
    private String mensaje;

    private manejadorConexiones() {
    }

    public manejadorConexiones(Socket socket) {
    }

    @Override
    public void run() {
        while (this.isAlive()) {
            try {
                DataInputStream sin = new DataInputStream(connection.getInputStream());
                DataOutputStream sout = new DataOutputStream(connection.getOutputStream());

                DataInputStream myin = new DataInputStream(System.in);

                while (true) {
                    mensaje = sin.readUTF();
                    System.out.println(mensaje);
                    sout.writeUTF(myin.readLine());
                }
            } catch (Exception ex) {
            }
        }
    }

    public String getMensaje() {
        return mensaje;
    }
    
}